package com.csu.csumall.security;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.csu.csumall.entity.User;
import com.csu.csumall.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImp implements UserDetailsService {


    private final UserMapper userMapper;

    @Autowired
    public UserDetailsServiceImp(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        int rows = userMapper.selectCount(Wrappers.<User>query().eq("username",username));
        if(rows == 1) {
            User user = userMapper.selectOne(
                    Wrappers.<User>query().eq("username", username)
            );
            return user;
        }
        throw new UsernameNotFoundException("User '" + username + "'not found");

    }
}
